#include "pagedatamonitor.h"
#include "ui_pagedatamonitor.h"
#include <QDateTime>
#include <QHeaderView>
#include <QTableWidgetItem>
#include <QSqlField>
#include <QMessageBox>
#include "devicemanagement.h"
#include <QDebug>

pageDataMonitor::pageDataMonitor(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::pageDataMonitor),
    m_dataMonitor(new DataMonitor(this))
{
    ui->setupUi(this);

    // 初始化表格
    setupRealTimeTable();
    setupHistoryTable();

    // 设置时间范围（默认最近24小时）
    ui->dateStart->setDateTime(QDateTime::currentDateTime().addDays(-1));
    ui->dateEnd->setDateTime(QDateTime::currentDateTime());
    ui->dateStart->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    ui->dateEnd->setDisplayFormat("yyyy-MM-dd HH:mm:ss");

    // 设置输入提示
    ui->lineDeviceId->setPlaceholderText("留空或0表示所有设备");
    ui->lineFilterRealTime->setPlaceholderText("输入设备ID过滤");

    // 连接信号槽
    if (connect(m_dataMonitor, &DataMonitor::newDataAvailable,
            this, &pageDataMonitor::onNewDataAvailable)) {
        qDebug() << "Signal-slot connection for newDataAvailable succeeded.";
    } else {
        qDebug() << "Signal-slot connection for newDataAvailable failed.";
    }
    connect(ui->btnQuery, &QPushButton::clicked,
            this, &pageDataMonitor::onQueryButtonClicked);
    connect(ui->btnFilterRealTime, &QPushButton::clicked,
            this, &pageDataMonitor::onRealTimeFilterClicked);

    // 启动监控
    m_dataMonitor->startMonitoring();

    // 初始化时显示实时数据
    updateRealTimeDisplay();
}

pageDataMonitor::~pageDataMonitor() {
    delete ui;
}

// 初始化实时数据表格（确保设备ID列完整显示）
void pageDataMonitor::setupRealTimeTable() {
    ui->tableRealTime->setColumnCount(7);
    ui->tableRealTime->setHorizontalHeaderLabels(
        {"时间", "设备ID", "温度(℃)", "湿度(%)", "光照(Lux)", "CO2(ppm)", "气压(hPa)"}
    );
    ui->tableRealTime->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); // 设备ID列自适应宽度
    ui->tableRealTime->horizontalHeader()->setStretchLastSection(true); // 最后一列填充剩余空间
    ui->tableRealTime->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

// 初始化历史数据表格（同上）
void pageDataMonitor::setupHistoryTable() {
    ui->tableHistory->setColumnCount(7);
    ui->tableHistory->setHorizontalHeaderLabels(
        {"时间", "设备ID", "温度(℃)", "湿度(%)", "光照(Lux)", "CO2(ppm)", "气压(hPa)"}
    );
    ui->tableHistory->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    ui->tableHistory->horizontalHeader()->setStretchLastSection(true);
    ui->tableHistory->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

// 设备ID验证（允许输入0表示所有设备）
bool pageDataMonitor::validateDeviceId(int deviceId) {
    if (deviceId < 0) {
        QMessageBox::warning(this, "错误", "设备ID不能为负数");
        return false;
    }
    if (deviceId == 0) return true;

    DeviceManagement deviceManager;
    if (!deviceManager.deviceExists(deviceId)) {
        QMessageBox::warning(this, "错误", QString("设备ID %1 不存在").arg(deviceId));
        return false;
    }
    return true;
}

// 实时数据过滤
void pageDataMonitor::onRealTimeFilterClicked() {
    int filterId = ui->lineFilterRealTime->text().toInt();
    if (!validateDeviceId(filterId)) return;
    updateRealTimeDisplay(filterId);
}

// 更新实时数据显示（确保每行对应单一设备ID）
void pageDataMonitor::updateRealTimeDisplay(int filterId) {
    qDebug() << "Updating real-time display with filter ID:" << filterId;
    ui->tableRealTime->setRowCount(0);
    for (const QSqlRecord &record : m_realTimeCache) {
        int currentId = record.value("device_id").toInt();
        if (filterId > 0 && currentId != filterId) {
            qDebug() << "Filtered out device ID:" << currentId;
            continue;
        }

        int row = ui->tableRealTime->rowCount();
        ui->tableRealTime->insertRow(row);
        ui->tableRealTime->setItem(row, 0, new QTableWidgetItem(record.value("timestamp").toString()));
        ui->tableRealTime->setItem(row, 1, new QTableWidgetItem(QString::number(currentId))); // 显示独立设备ID
        ui->tableRealTime->setItem(row, 2, new QTableWidgetItem(QString::number(record.value("temperature").toDouble(), 'f', 1)));
        ui->tableRealTime->setItem(row, 3, new QTableWidgetItem(QString::number(record.value("humidity").toDouble(), 'f', 1)));
        ui->tableRealTime->setItem(row, 4, new QTableWidgetItem(QString::number(record.value("light").toDouble(), 'f', 0)));
        ui->tableRealTime->setItem(row, 5, new QTableWidgetItem(QString::number(record.value("co2").toDouble(), 'f', 0)));
        ui->tableRealTime->setItem(row, 6, new QTableWidgetItem(QString::number(record.value("pressure").toDouble(), 'f', 1)));
        qDebug() << "Added row for device ID:" << currentId;
    }
    ui->tableRealTime->scrollToBottom();
}

// 接收新数据（确保绑定单一设备ID）
void pageDataMonitor::onNewDataAvailable(int deviceId, double temperature, double humidity,
                                       double light, double co2, double pressure) {
    qDebug() << "Received new data for device ID:" << deviceId;
    QSqlRecord newRecord;
    newRecord.append(QSqlField("device_id", QVariant::Int));
    newRecord.append(QSqlField("timestamp", QVariant::String));
    newRecord.append(QSqlField("temperature", QVariant::Double));
    newRecord.append(QSqlField("humidity", QVariant::Double));
    newRecord.append(QSqlField("light", QVariant::Double));
    newRecord.append(QSqlField("co2", QVariant::Double));
    newRecord.append(QSqlField("pressure", QVariant::Double));

    newRecord.setValue("device_id", deviceId);
    newRecord.setValue("timestamp", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    newRecord.setValue("temperature", temperature);
    newRecord.setValue("humidity", humidity);
    newRecord.setValue("light", light);
    newRecord.setValue("co2", co2);
    newRecord.setValue("pressure", pressure);

    m_realTimeCache.append(newRecord);
    qDebug() << "Added new record to cache. Cache size:" << m_realTimeCache.size();
    updateRealTimeDisplay(ui->lineFilterRealTime->text().toInt());
}

// 查询历史数据（动态构造SQL）
void pageDataMonitor::onQueryButtonClicked() {
    int deviceId = ui->lineDeviceId->text().toInt(); // 输入0表示所有设备
    if (!validateDeviceId(deviceId)) return;

    QString startTime = ui->dateStart->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    QString endTime = ui->dateEnd->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    QList<QSqlRecord> records = m_dataMonitor->queryHistoricalData(deviceId, startTime, endTime);
    populateHistoryTable(records);
}

// 填充历史数据表格（确保每行对应单一设备ID）
void pageDataMonitor::populateHistoryTable(const QList<QSqlRecord> &records) {
    ui->tableHistory->setRowCount(0);
    for (const QSqlRecord &record : records) {
        int row = ui->tableHistory->rowCount();
        ui->tableHistory->insertRow(row);
        ui->tableHistory->setItem(row, 0, new QTableWidgetItem(record.value("timestamp").toString()));
        ui->tableHistory->setItem(row, 1, new QTableWidgetItem(record.value("device_id").toString())); // 显示独立设备ID
        ui->tableHistory->setItem(row, 2, new QTableWidgetItem(QString::number(record.value("temperature").toDouble(), 'f', 1)));
        ui->tableHistory->setItem(row, 3, new QTableWidgetItem(QString::number(record.value("humidity").toDouble(), 'f', 1)));
        ui->tableHistory->setItem(row, 4, new QTableWidgetItem(QString::number(record.value("light").toDouble(), 'f', 0)));
        ui->tableHistory->setItem(row, 5, new QTableWidgetItem(QString::number(record.value("co2").toDouble(), 'f', 0)));
        ui->tableHistory->setItem(row, 6, new QTableWidgetItem(QString::number(record.value("pressure").toDouble(), 'f', 1)));
    }
}
